<template>
  <div class="uploading" id="container">
    <div class="uploading_tab" v-show="uploadType === 1">
      <div class="uploading_tab_item">
        <img :src="TAB02" alt="" width="100%" />
        <span class="tab_title">上传车票图片</span>
        <img :src="title01" alt="" class="tab_tag" />
      </div>

      <div class="uploading_tab_item" @click="uploadType = 2">
        <img :src="TAB01" alt="" width="100%" @click="uploadType = 2" />
        <span class="tab_title title2">填写车票信息</span>
        <img :src="title02" alt="" class="tab_tag tag2" />
      </div>
    </div>

    <div class="uploading_tab" v-show="uploadType === 2">
      <div class="uploading_tab_item" @click="uploadType = 1">
        <img :src="TAB03" alt="" width="100%" @click="uploadType = 1" />
        <span class="tab_title title2">上传车票图片</span>
        <img :src="title01" alt="" class="tab_tag" />
      </div>

      <div class="uploading_tab_item">
        <img :src="TAB04" alt="" width="100%" />
        <span class="tab_title ">填写车票信息</span>
        <img :src="title02" alt="" class="tab_tag tag2" />
      </div>
    </div>
    <div class="uploading_white">
      <div class="uploading_con">
        <template v-if="uploadType === 1">
          <div class="title require">
            车票图片
            <div class="tips">
              本人实体票照片或电子票截图，
              <span class="guide" @click="lookGuide">查看示例>> </span>
            </div>
          </div>

          <van-uploader
            class="upload"
            v-model="fileList"
            :max-count="1"
            :before-read="beforeRead"
          >
            <van-button icon="plus" class="upload_btn"></van-button>
          </van-uploader>

          <div class="title">车票故事</div>
          <van-field
            class="uploading_textarea"
            v-model="story"
            ref="textArea"
            rows="3"
            :autosize="{ maxHeight: 180, minHeight: 180 }"
            label=""
            type="textarea"
            maxlength="200"
            placeholder="仅限中文和标点符号, 写车票故事更容易中奖哦！"
            show-word-limit
            @blur="refreshPage"
          />
        </template>

        <template v-if="uploadType === 2">
          <van-field
            readonly
            clickable
            label="乘坐时间"
            class="uploading-field__input"
            label-class="uploading-field require"
            :value="app.dptDate"
            placeholder="请选择乘坐日期  >"
            input-align="right"
            @click="openTimePicker"
          />

          <van-field
            readonly
            clickable
            label="乘坐项目"
            :value="app.project"
            class="uploading-field__input"
            label-class="uploading-field require"
            placeholder="请选择项目类型  >"
            input-align="right"
            @click="openProgramPicker"
          />

          <van-field
            label="车票金额（元）"
            v-model="amount"
            maxlength="7"
            class="uploading-field__input"
            label-class="uploading-field require"
            input-align="right"
            label-width="100px"
            ref="amount"
            type="number"
            placeholder="请输入乘坐金额 "
          />

          <div class="tips tips-cbd">
            不记得乘坐信息？<span class="guide" @click="seeOrderList"
              >查看订单>>
            </span>
          </div>
        </template>
      </div>

      <div class="uploading-submit pluse_ani" @click="submit">
        {{ wiredText }}
      </div>
      <div class="uploading-rule">点击上传视为同意活动规则</div>
    </div>
    <!-- 
    <div class="inner_wrapper" v-if="showTimePicker || showProgramPicker">
 
    </div> -->
  </div>
</template>

<script>
import {
  Uploader,
  Form,
  Field,
  DatetimePicker,
  Popup,
  Picker,
  Toast,
  Dialog,
  Button
} from "vant";
import compress from "@/utils/compressor";
import { envFunc, getEnv } from "@/utils/util";
import { uploadApi, textfraud } from "@/service";
import {
  TAB01,
  TAB02,
  TAB03,
  TAB04,
  // TAB5,
  // TAB6,
  title01,
  title02
} from "@/constant";
import { cbdGetClientInfo, wxGetPhone } from "@/utils/login";

// 正则表达式  中文 标点符号(中英文) 空格
/*eslint-disable*/
const testReg = /^[\s|\u4e00-\u9fa5|\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'<>~\·`\?:;|]*$/;

// 判断是否是 两位小数以下
const roundInfo = (str = "") => {
  let decimal = str.split(".")[1];
  if (!decimal || decimal.length <= 2) {
    return true;
  } else return false;
};

let i = 0
export default {
  components: {
    [Uploader.name]: Uploader,
    [Form.name]: Form,
    [Field.name]: Field,
    [DatetimePicker.name]: DatetimePicker,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Button.name]: Button
  },
  data: function() {
    return {
      fileList: [],
      uploadType: 1, // 1-图片；2-订单
      story: "",
      dptDate: "",
      project: "",
      amount: "",
      showTimePicker: false,
      showProgramPicker: false,

      TAB01,
      TAB02,
      TAB03,
      TAB04,
      // TAB5,
      // TAB6,
      title01,
      title02
    };
  },
  methods: {
    refreshPage() {
      // debugger;
      // this.app.bs.refresh();
      window.scroll(0, 10)
    },
    openProgramPicker() {
      this.$store.commit("changeProgramPicker", true);
    },

    openTimePicker() {
      this.$store.commit("changeTimePicker", true);
    },
    lookGuide() {
      envFunc(
        () => {
          bridge.naviPlugins.openWebPage({
            webPageUrl:
              "https://zhuanti.chebada.com/act/h5/dc4135a3468fa9caaa93f6295d454918/"
          });
        },
        () => {

          wx.miniProgram.navigateTo({
            url: `/pages/webview/webview?url=${encodeURIComponent('https://zhuanti.chebada.com/act/h5/dc4135a3468fa9caaa93f6295d454918/')}`
          });
          // location.href =
          //   "https://zhuanti.chebada.com/act/h5/dc4135a3468fa9caaa93f6295d454918/";
        }
      );
    },
    seeOrderList() {
      envFunc(
        () => {
          bridge.naviPlugins.openWebPage({
            webPageUrl: "cbdbusbutler://GTPApp/OrderList?forceBack=0"
          });
        },
        () => {
          wx.miniProgram.navigateTo({
            url: "/pages/bus/order/order?category=0"
          });
        }
      );
    },

    confirmCity(e) {
      this.project = e;
      this.showProgramPicker = false;
    },
    async beforeRead(file) {
      const { size } = file;

      return new Promise(async (resolve, reject) => {
        if (size < 1000 * 1024) return resolve(file);

        try {
          const img = await compress(file, 0.5);
          console.log(img.size / 1024);

          return resolve(img);
        } catch (e) {
          reject(e);
        }
      });
    },

    // 检查违规词语
    checkStory(e) {
      return testReg.test(e);
    },
    // 查看表单规则
    checkRule() {
      const { uploadType, fileList, story, amount } = this;
      const dptDate = this.app.dptDate;
      const project = this.app.project;
      if (uploadType === 1) {
        if (fileList.length === 0) {
          Toast("图片不能为空");
          return false;
        }

        // 如果 story 为空 不进行判断

        if (!story) return true;
        if (story && !this.checkStory(story)) {
          Toast("仅支持输入中文和标点符号");
          return false;
        }

        // TODO: 支持输入中文和标点符号
      } else {
        if (!dptDate) {
          Toast("请选择乘坐时间");
          return false;
        }

        if (!project) {
          Toast("请选择乘车项目");
          return false;
        }

        if (!amount || !roundInfo(amount + "")) {
          Toast("请填写正确格式车票金额");
          return false;
        }
        // 金额不能大于 666
        // if (Number(amount) > 666) {
        //   Toast("请填写正确格式车票金额");
        //   return false;
        // }
      }

      return true;
    },
    async uploadInfo() {
      // 获取手机号
      let phone;
      let env = await getEnv();
      if (env === "cbd") {
        const { mobileNo } = await cbdGetClientInfo();
        phone = mobileNo;
      } else if (env === "mini") {
        phone = wxGetPhone();
      }
      // else if (env === "h5") {
      //   phone = "15261056568";
      // }
      let params = { uploadType: this.uploadType, mobileNo: phone };

      if (this.uploadType === 1) {
        let file = this.fileList[0];
        let imgBase64 = file.content;

        params = { ...params, imgBase64, story: this.story };
      } else
        params = {
          ...params,
          dptDate: this.app.dptDate,
          project: this.app.project,
          amount: this.amount
        };

      try {
        await uploadApi(params);
        this.$store.dispatch("main");
        Toast("您已成功上传，等待开奖");
      } catch (e) {
        console.log(e);
      }
    },
    async submit() {
      // this.$nextTick(() => {
      //   this.app.bs.refresh();
      // });
     
      const { uploadType, story } = this;

       // 提交后 隐藏键盘
      // window.scrollTo(0,0) // 提交后 隐藏键盘
      
      if (uploadType === 1) {
        this.$refs.textArea.blur()
        setHmt("upload", "read");
      } else if (uploadType === 2) {
        this.$refs.amount.blur()
        setHmt("upload", "information");
      }



      // 判断是否符合规则
      if (!this.checkRule()) return;
      // 调用同程接口判断
      if (story && uploadType === 1) {
        let res = await this.textfraudWrap({ text: story });
        if (!res) return Toast("您的故事含有违规词语，请重新输入");
      }

      Dialog.confirm({
        title: "上传后会校验真实性",
        message: "且不能更改，确定上传吗？",
        confirmButtonText: "确定",
        cancelButtonText: "稍后上传"
      })
        .then(() => {
          // on confirm
          this.uploadInfo();
        })
        .catch(() => {
          // on cancel
          setHmt("home", "later");
        });
    },
    async textfraudWrap(e) {
      try {
        let {
          data: { code, riskLevel }
        } = await textfraud(e);

        if (code == "100" || riskLevel == "PASS") return true;
        else false;
      } catch (e) {
        return false;
      }
    }
  },
  computed: {
    wiredText() {
      return "上传信息 赢取报销";
    },
    app() {
      return this.$store.state.app;
    }
  },
  mounted() {
  },
  watch: {
    story: function(val) {
      if (val && i == 0) {
          this.$refs.textArea.$el.addEventListener("touchmove", function(e) {
            e.stopPropagation();
            console.log(222);
          });
          i += 1
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/app.scss";
.uploading {
  .uploading_white {
    padding-bottom: 53px;
    border-radius: 0 0 25px 25px;
    background: #fff;
  }
  .uploading_tab {
    background: transparent;
    line-height: 0;
    @include flex_config(center, center, row);

    .uploading_tab_item {
      position: relative;
      width: 50%;

      .tab_tag {
        position: absolute;
        top: 10px;
        right: 20px;
        width: 115px;
      }

      .tag2 {
        right: 30px;
        width: 188px;
      }

      .tab_title {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        transform: translate(-50%, -50%);
        text-align: center;
        font-size: 36px;
        font-weight: 800;
        color: #1d1d1d;
        margin-top: 0 !important;
      }
      .title2 {
        color: #767676;
        font-weight: 500;
      }
    }
  }
  .uploading_con {
    padding: 20px 50px;
    background: #fff;
  }
  .title {
    font-size: 34px;
    font-weight: 800;
    color: #222222;
    line-height: 66px;
    @include flex_config(space-between, center, row);
  }

  .tips {
    font-size: 20px;
    font-weight: 500;
    color: #555555;
    text-align: center;
    @include flex_config(flex-start, flex-end, row);

    .guide {
      font-size: 24px;

      font-weight: 500;
      text-decoration: underline;
      color: #ef3a26;
    }
  }

  .upload {
    margin-top: 18px;
    margin-bottom: 58px;
    .upload_btn {
      width: 187px;
      height: 159px;
      background: #f4f4f4;
      border: 1px solid #f0f0f0;
      border-radius: 10px;
      font-size: 50px;
      font-weight: 400;
    }
  }

  .uploading_textarea {
    background: #f7f7f7;
    border: 1px solid rgba(191, 191, 191, 0.24);

    border-radius: 10px;
  }

  .uploading-submit {
    width: 454px;
    height: 110px;
    margin: 36px auto 23px auto;
    background: linear-gradient(90deg, #fd6645, #f93f2b);
    border-radius: 55px;
    font-size: 34px;

    font-weight: 800;
    color: #ffffff;
    line-height: 110px;
    text-align: center;
  }

  .uploading-rule {
    font-size: 20px;

    font-weight: 400;
    color: #999999;
    text-align: center;
  }

  .tips-cbd {
    margin: 50px 0 80px 0;
  }

  .pluse_ani {
    animation: pulse infinite 1s;
  }
  @keyframes pulse {
    0% {
      // -webkit-transform: scale(1);
      transform: scale(1);
    }

    50% {
      // -webkit-transform: scale(1.05);
      transform: scale(1.05);
    }

    100% {
      // -webkit-transform: scale(1);
      transform: scale(1);
    }
  }
}

.inner_wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  // z-index: -1;
}
</style>

<style lang="scss">
@import "@/app.scss";

.uploading-field {
  width: 230px !important;
  font-size: 32px;
  font-weight: 800;
  color: #222222;
  padding: 22px 0;
}

.require {
  position: relative;

  &:before {
    content: "*";
    position: absolute;
    width: 16px;

    left: -23px;
    top: 50%;
    color: #eb5949;
    transform: translate(0, -50%);
  }
}

.uploading-field__input {
  .van-field__value {
    @include flex_config(flex-end, center, row);
  }
}

// .uploading {
// .van-overlay {
//   height: 100vh !important;
// }

// .van-popup {
//   position: absolute !important;
// }
// }
</style>
